<template>
  <div class="announcement-list-container">
    <el-card class="announcement-list-card">
      <template #header>
        <div class="card-header">
          <h2>公告列表</h2>
        </div>
      </template>
      
      <el-empty v-if="announcements.length === 0" description="暂无公告" />
      
      <div v-else class="announcement-list">
        <el-timeline>
          <el-timeline-item
            v-for="item in announcements"
            :key="item.id"
            :timestamp="formatDate(item.publishTime || item.createTime)"
            placement="top"
            :type="item.isPublished ? 'primary' : 'info'"
          >
            <el-card class="announcement-item" shadow="hover">
              <template #header>
                <div class="announcement-header">
                  <router-link 
                    v-if="isAuthenticated" 
                    :to="`/announcements/${item.id}`" 
                    class="announcement-title"
                  >
                    {{ item.title }}
                  </router-link>
                  <span 
                    v-else 
                    class="announcement-title clickable" 
                    @click="handleTitleClick(item.id)"
                    :title="'点击查看详情（需要登录）'"
                  >
                    {{ item.title }}
                    <el-icon class="lock-icon"><Lock /></el-icon>
                  </span>
                </div>
              </template>
              <div class="announcement-content">
                <p>{{ truncateText(item.content, 150) }}</p>
              </div>
              <div class="announcement-footer">
                <router-link 
                  v-if="isAuthenticated" 
                  :to="`/announcements/${item.id}`" 
                  class="read-more"
                >
                  查看详情 <el-icon><ArrowRight /></el-icon>
                </router-link>
                <span 
                  v-else 
                  class="read-more clickable" 
                  @click="handleDetailClick(item.id)"
                >
                  查看详情 <el-icon><Lock /></el-icon>
                </span>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-if="total > 0"
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { ArrowRight, Lock } from '@element-plus/icons-vue'

export default {
  name: 'AnnouncementList',
  components: {
    ArrowRight,
    Lock
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    
    // 获取登录状态
    const isAuthenticated = computed(() => store.getters.isAuthenticated)
    
    // 公告列表相关数据
    const announcements = computed(() => store.getters.publicAnnouncements)
    const total = computed(() => store.state.announcements.totalPublic)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    /**
     * 获取公告列表
     */
    const fetchAnnouncements = async () => {
      await store.dispatch('fetchPublicAnnouncements', {
        page: currentPage.value,
        size: pageSize.value
      })
    }
    
    /**
     * 处理未登录用户点击标题
     */
    const handleTitleClick = (announcementId) => {
      showLoginPrompt(announcementId)
    }
    
    /**
     * 处理未登录用户点击查看详情
     */
    const handleDetailClick = (announcementId) => {
      showLoginPrompt(announcementId)
    }
    
    /**
     * 显示登录提示弹窗
     */
    const showLoginPrompt = (announcementId) => {
      ElMessageBox.confirm(
        '此公告内容需要登录后才能查看，是否现在登录？',
        '需要登录',
        {
          confirmButtonText: '立即登录',
          cancelButtonText: '取消',
          type: 'info',
          center: true
        }
      ).then(() => {
        // 用户点击登录，跳转到登录页面，并设置回调地址
        router.push({
          name: 'Login',
          query: { redirect: `/announcements/${announcementId}` }
        })
      }).catch(() => {
        // 用户取消，什么都不做
      })
    }
    
    // 初始化
    onMounted(() => {
      fetchAnnouncements()
    })
    
    // 分页处理
    const handlePageChange = (page) => {
      currentPage.value = page
      fetchAnnouncements()
    }
    
    // 文本截断
    const truncateText = (text, length) => {
      if (!text) return ''
      if (text.length <= length) return text
      return text.substring(0, length) + '...'
    }
    
    // 日期格式化
    const formatDate = (dateString) => {
      if (!dateString) return '未发布'
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
    
    return {
      isAuthenticated,
      announcements,
      total,
      currentPage,
      pageSize,
      truncateText,
      formatDate,
      handlePageChange,
      handleTitleClick,
      handleDetailClick
    }
  }
}
</script>

<style scoped>
.announcement-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.announcement-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #303133;
}

.announcement-list {
  margin-top: 20px;
}

.announcement-item {
  margin-bottom: 15px;
  transition: all 0.3s;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.announcement-title {
  font-size: 1.2rem;
  color: #303133;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s;
}

.announcement-title:hover {
  color: #409EFF;
}

.announcement-content {
  color: #606266;
  margin: 10px 0;
  line-height: 1.6;
}

.announcement-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.read-more {
  display: flex;
  align-items: center;
  color: #409EFF;
  text-decoration: none;
  font-size: 0.9rem;
  transition: color 0.3s;
}

.read-more:hover {
  color: #66b1ff;
}

.read-more .el-icon {
  margin-left: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.text-muted {
  color: #909399;
  font-size: 0.9rem;
}

/* 新增：可点击样式和锁定图标 */
.clickable {
  cursor: pointer;
  transition: color 0.3s;
}

.clickable:hover {
  color: #409EFF;
}

.lock-icon {
  margin-left: 5px;
  font-size: 0.9rem;
  opacity: 0.7;
}

.announcement-title.clickable {
  display: flex;
  align-items: center;
}

.read-more.clickable {
  display: flex;
  align-items: center;
}
</style> 